package com.chinaV.uitls;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection {
    private final String CONFIG_PATH = "../config/database.xml";


    // 数据库连接
    private Connection conn;

    // 数据库
    private Statement st;


    {
        System.out.println("数据库初始化开始！");
        getConnection();
        getStatement();
        System.out.println("数据库初始化完毕！");
    }

    public DBConnection() {

    }

    private Element getXMLConfig() {
        // 获取 XML 文件的路径
        String filePath = DBConnection.class.getResource(CONFIG_PATH).getPath();

        // 创建 SAXReader 对象
        SAXReader reader = new SAXReader();

        // 读取 XML 文件
        Document document = null;
        try {
            document = reader.read(new File(filePath));
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        // 获取根元素
        Element root = document.getRootElement();

        return root;
    }

    public void getConnection() {

        Element root = getXMLConfig();


        try {
            Class.forName(root.element("driver").getText());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String jdbcUrl = root.element("url").getText();
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(jdbcUrl,
                    root.element("username").getText(),
                    root.element("password").getText());
            this.conn = conn;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (null == conn) {
            System.out.println("数据库连接失败，请检查数据库配置是否正确！");
        }

    }

    public void getStatement() {
        try {
            this.st = this.conn.createStatement();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            this.st = null;
        }
    }

    public Connection getConn() {
        return conn;
    }


    public Statement getSt() {
        return st;
    }


}
